<template>
  <view class="container">
    <!-- 表格配置区 -->
      <text class="config-text">当前表格：{{rows}}行 × {{cols}}列</text>
      <text class="range-text" v-if="queryStart && queryEnd">预设选择范围：{{queryStart}} 到 {{queryEnd}}</text>
      <text class="range-text">当前起始点：{{visualStartCell}} 结束点：{{visualEndCell}}</text>
      <text class="range-text" v-if="currentRangeId">当前选中范围ID: {{currentRangeId}}</text>

    <!-- 操作区 -->
    <view class="action-area" v-if="cells.length > 0">
      <view class="action-buttons">
        <u-button type="primary" size="small" @click="selectByQueryRange" v-if="queryStart && queryEnd">应用预设选择</u-button>
        <u-button :type="clickSelectButtonType" size="small" @click="toggleClickSelectMode">
          {{ clickSelectButtonText }}
        </u-button>
        <u-button size="small" @click="clearSelection">清除选择</u-button>
      </view>
      <view class="status-display" v-if="isClickSelectModeActive">
        点击选择模式：{{ clickSelectStatusText }}
      </view>
    </view>

    <!-- 表格 - 使用兼容微信小程序的布局 -->
    <view class="table-wrapper" v-if="cells.length > 0">
      <view class="table">
        <view class="row" v-for="(row, rowIndex) in tableRows" :key="rowIndex">
          <view 
            v-for="cell in row" 
            :key="cell.number"
            class="cell"
            :class="{
              selected: isCellSelected(cell.number),
              'start-cell': cell.number === visualStartCell,
              'end-cell': cell.number === visualEndCell
            }"
            @click="handleCellClick(cell.number)"
          >
            {{ cell.number }}
            <view v-if="cell.number === visualStartCell" class="cell-label start">起</view>
            <view v-if="cell.number === visualEndCell" class="cell-label end">终</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      rows: 6,
      cols: 6,
      cells: [],
      tableRows: [], // 二维数组用于表格布局
      selectedCells: {},
      clickSelectMode: 'inactive',
      selectionStart: null,
      selectionEnd: null,
      visualStartCell: null,
      visualEndCell: null,
      queryStart: null,
      queryEnd: null,
      ranges: [],
      currentRangeId: null
    }
  },
  computed: {
    maxCellNumber() {
      return this.rows * this.cols
    },
    isClickSelectModeActive() {
      return this.clickSelectMode !== 'inactive'
    },
    clickSelectStatusText() {
      return {
        inactive: '',
        selectingStart: '请点击起始点',
        selectingEnd: '请点击结束点'
      }[this.clickSelectMode]
    },
    clickSelectButtonText() {
      return this.isClickSelectModeActive ? '取消点击选择' : '点击选择'
    },
    clickSelectButtonType() {
      return this.isClickSelectModeActive ? 'warning' : 'default'
    }
  },
  methods: {
    initGrid() {
      this.cells = []
      for (let i = 1; i <= this.maxCellNumber; i++) {
        this.cells.push({ number: i })
      }
      this.resetAllSelection()
      
      // 创建二维数组结构，兼容微信小程序的布局限制
      this.tableRows = [];
      for (let i = 0; i < this.rows; i++) {
        const row = [];
        for (let j = 0; j < this.cols; j++) {
          const index = i * this.cols + j;
          if (index < this.cells.length) {
            row.push(this.cells[index]);
          }
        }
        this.tableRows.push(row);
      }
      
      if (this.queryStart && this.queryEnd) {
        this.$nextTick(() => {
          this.selectByQueryRange()
        })
      }
    },

    getQueryParams() {
      // 模拟从URL获取参数
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      if (currentPage) {
        this.rows = parseInt(currentPage.options.rows) || 6
        this.cols = parseInt(currentPage.options.cols) || 6
        this.queryStart = parseInt(currentPage.options.start)
        this.queryEnd = parseInt(currentPage.options.end)
      }
      
      // 模拟范围数据
      this.ranges = [
        { start: 5, end: 10, id: 'RNG2023-001' },
        { start: 15, end: 20, id: 'RNG2023-002' },
        { start: 25, end: 30, id: 'RNG2023-003' }
      ]
    },

    selectByQueryRange() {
      if (!this.queryStart || !this.queryEnd) return
      
      const start = Math.max(1, Math.min(this.queryStart, this.maxCellNumber))
      const end = Math.max(1, Math.min(this.queryEnd, this.maxCellNumber))
      
      // 查找范围ID
      const range = this.ranges.find(r => 
        (r.start === start && r.end === end) || 
        (r.start === end && r.end === start)
      )
      
      this.selectRange(start, end, range ? range.id : null)
      uni.showToast({
        title: `已应用选择范围 ${start} 到 ${end}`,
        icon: 'none'
      })
    },

    handleCellClick(cellNumber) {
      if (this.isClickSelectModeActive) {
        if (this.clickSelectMode === 'selectingStart') {
          this.selectionStart = cellNumber
          this.visualStartCell = cellNumber
          this.clickSelectMode = 'selectingEnd'
          this.clearVisualEndPoint()
        } else if (this.clickSelectMode === 'selectingEnd') {
          this.selectionEnd = cellNumber
          this.visualEndCell = cellNumber
          this.selectRange(this.selectionStart, this.selectionEnd, `自定义-${Date.now()}`)
          this.clickSelectMode = 'inactive'
          uni.showToast({
            title: `已选择范围: ${Math.min(this.selectionStart, this.selectionEnd)} 到 ${Math.max(this.selectionStart, this.selectionEnd)}`,
            icon: 'success',
            duration: 1500
          })
        }
      } else {
        // 非选择模式下点击单元格显示范围ID
        const rangeId = this.getRangeIdByCell(cellNumber)
        if (rangeId) {
          this.currentRangeId = rangeId
          uni.showToast({
            title: `范围ID: ${rangeId}`,
            icon: 'none',
            duration: 2000
          })
        }
      }
    },
    
    // 根据单元格编号获取范围ID
    getRangeIdByCell(cellNumber) {
      const range = this.ranges.find(r => {
        const start = Math.min(r.start, r.end)
        const end = Math.max(r.start, r.end)
        return cellNumber >= start && cellNumber <= end
      })
      return range ? range.id : null
    },

    toggleClickSelectMode() {
      if (this.isClickSelectModeActive) {
        this.resetClickSelection()
      } else {
        this.clickSelectMode = 'selectingStart'
        uni.showToast({
          title: '请依次点击起始点和结束点',
          icon: 'none',
          duration: 2000
        })
      }
    },

    selectRange(start, end, id = null) {
      const min = Math.min(start, end)
      const max = Math.max(start, end)
      
      const newSelection = {}
      for (let i = min; i <= max; i++) {
        newSelection[i] = true
      }
      this.selectedCells = newSelection
      
      this.visualStartCell = min
      this.visualEndCell = max
      
      // 保存ID和范围信息
      if (id) {
        this.currentRangeId = id
        // 添加到范围列表
        if (!this.ranges.some(r => r.id === id)) {
          this.ranges.push({
            start: min,
            end: max,
            id: id
          })
        }
      }
    },

    isCellSelected(cellNumber) {
      return !!this.selectedCells[cellNumber]
    },

    clearSelection() {
      this.selectedCells = {}
      this.selectionStart = null
      this.selectionEnd = null
      this.visualStartCell = null
      this.visualEndCell = null
      this.currentRangeId = null
      uni.showToast({
        title: '已清除所有选择',
        icon: 'none'
      })
    },

    clearVisualEndPoint() {
      this.visualEndCell = null
    },

    resetClickSelection() {
      this.clickSelectMode = 'inactive'
      this.selectionStart = null
      this.selectionEnd = null
    },

    resetAllSelection() {
      this.clearSelection()
      this.resetClickSelection()
    }
  },
  onLoad() {
    this.getQueryParams()
    this.initGrid()
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
}

.config-area {
  background: white;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.config-text {
  font-size: 32rpx;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
  font-weight: bold;
}

.range-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.error-text {
  font-size: 28rpx;
  color: #ff6b6b;
  display: block;
  margin-top: 8rpx;
}

.action-area {
  background: white;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200rpx, 1fr));
  gap: 20rpx;
  margin-top: 20rpx;
}

.status-display {
  margin-top: 24rpx;
  padding: 16rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #666;
}

.table-wrapper {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  flex: 1;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: auto;
}

/* 表格样式 - 使用Flex布局兼容微信小程序 */
.table {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.row {
  display: flex;
  width: 100%;
  margin-bottom: 4rpx;
}

.row:last-child {
  margin-bottom: 0;
}

.cell {
  flex: 1;
  min-height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
  font-size: 32rpx;
  position: relative;
  /* transition: all 0.3s ease; */
}

.cell.selected {
  background-color: #7ec699;
  font-weight: bold;
}

.cell-label {
  position: absolute;
  top: 6rpx;
  right: 6rpx;
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.start {
  background: #ff6b6b;
}

.end {
  background: #5c7cfa;
}

/* 按钮样式 */
.u-button {
  border-radius: 12rpx;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .cell {
    font-size: 28rpx;
    min-height: 72rpx;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
  }
}
</style>